package com.xu.t1.middleware.threadallocation;

import com.xu.t1.middleware.Thread.ThreadCounterService;
import com.xu.t1.model.ThreadAllocationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
public class ThreadHandler1 implements ThreadAllocationHandler {

    private ThreadAllocationHandler nextHandler;


    // 系统最大线程数
    private static final int MAX_THREADS = 20;

    @Autowired
    private ThreadCounterService threadCounterService;

    @Override
    public boolean handle(ThreadAllocationContext context) {

        // 获取当前系统线程数
        int currentThreads = threadCounterService.getThreadCount();
        context.setTotalThreads(currentThreads);


        int remainingThreads = MAX_THREADS - currentThreads;

        if (remainingThreads <= 0) {
            // 没线程可分配
            context.setAllocatableThreads(0);
            return false;
        } else if (remainingThreads == 1) {
            // 剩余1个线程 直接分配1个
            context.setAllocatableThreads(1);
            return false;
        } else {
            // 剩余线程多
            context.setAllocatableThreads(remainingThreads);
            if (nextHandler != null) {
                return nextHandler.handle(context);
            } else {
                return true;
            }
        }
    }

    @Override
    public ThreadAllocationHandler setNext(ThreadAllocationHandler nextHandler) {
        this.nextHandler = nextHandler;
        return nextHandler;
    }
}